package com.free.food.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.free.food.core.domain.ResultVO;
import com.free.food.core.enums.ResultEnum;
import com.free.food.core.exception.OrderException;
import com.free.food.core.util.ResultUtil;
import com.free.food.order.convert.CreateOrderRequest2OrderDTO;
import com.free.food.order.domain.dto.OrderDTO;
import com.free.food.order.domain.request.CreateOrderRequest;
import com.free.food.order.entity.OrderDetail;
import com.free.food.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019/2/14 11:11
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/create")
    public ResultVO<Map<String, Object>> create(@Valid CreateOrderRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确，request={}", request);
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = CreateOrderRequest2OrderDTO.convert(request);

        if (CollectionUtils.isEmpty(orderDTO.getOrderDetails())) {
            log.error("【创建订单】购物车信息为空，request={}", request);
            throw new OrderException(ResultEnum.CART_ISNULL);
        }

        OrderDTO result = orderService.create(orderDTO);
        Map<String, Object> data = new HashMap<>(16);
        data.put("orderId", result.getOrderId());
        return ResultUtil.success(data);
    }

    public static void main(String[] args) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setProductId("157875196366160022");
        orderDetail.setProductQuantity(2);
        OrderDetail orderDetail2 = new OrderDetail();
        orderDetail2.setProductId("157875227953464068");
        orderDetail2.setProductQuantity(2);

        List<OrderDetail> orderDetails = new ArrayList<>();
        orderDetails.add(orderDetail);
        orderDetails.add(orderDetail2);
        System.out.println(JSONObject.toJSONString(orderDetails));


    }


}
